package com.liesheng.haylou.ui.main;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Build;
import android.view.View;

import androidx.databinding.DataBindingUtil;

import com.liesheng.daemonlib.LogUtil;
import com.liesheng.haylou.R;
import com.liesheng.haylou.base.BaseActivity;
import com.liesheng.haylou.base.BaseVm;
import com.liesheng.haylou.bluetooth.BleUUIDs;
import com.liesheng.haylou.common.RxHelper;
import com.liesheng.haylou.databinding.ActivityDialogBinding;
import com.liesheng.haylou.db.entity.BoundedDevice;
import com.liesheng.haylou.event.DelDeviceEvent;
import com.liesheng.haylou.event.DialogCloseEvent;
import com.liesheng.haylou.utils.ToastUtil;
import com.liesheng.haylou.utils.sp.SpUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.UUID;


/**
 * Date:2019/11/15
 * <p>
 * Author:wuzhiguang
 * <p>
 * Description:
 * 后台服务搜索到蓝牙设备后弹窗
 */
public class DialogActivity extends BaseActivity<ActivityDialogBinding, BaseVm> {

    AnimationDrawable animationDrawable;
    BluetoothDevice device;
    String leftAddress, rightAddress;
    String advCount;
    String spKey;

    public BluetoothGattCallback mBluetoothGattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        ToastUtil.showToast("连接成功");
                        LogUtil.d("DialogActivity---连接成功");
                    }
                });
            }
        }

    };


    @Override
    protected ActivityDialogBinding getmBinding() {
        mBinding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.activity_dialog, null, false);
        overridePendingTransition(0, 0);
        return mBinding;
    }

    @Override
    protected boolean isRegistEventBus() {
        return true;
    }

    @Override
    protected BaseVm getViewModel() {
        return null;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventPost(DialogCloseEvent event) {
        if (event.rightLeftAddress.equals(spKey)) {
            finish();
        }
    }


    @Override
    protected void initData() {
        showHeadLayout(false);
        device = getIntent().getParcelableExtra("BluetoothDevice");
        leftAddress = getIntent().getStringExtra("leftAddress");
        rightAddress = getIntent().getStringExtra("rightAddress");
        advCount = getIntent().getStringExtra("advCount");
        spKey = (rightAddress + leftAddress).replaceAll(":", "");

        SpUtil.put(spKey, advCount);

        mBinding.title.setText(device.getName());
        String msg = "ble:" + device.getAddress() + "左:" + leftAddress + "     右:" + rightAddress;
        mBinding.message.setText(msg);

//        mBinding.btnCancel.setText("连接左耳机");
//        mBinding.btnSubmit.setText("连接右耳机");

        mBinding.iv.setImageResource(R.drawable.animation_rotate);
        animationDrawable = (AnimationDrawable) mBinding.iv.getDrawable();
        animationDrawable.start();
    }

    @Override
    public void onClickView(View view) {
        switch (view.getId()) {
            case R.id.btn_cancel:
                finish();
//                connect(leftAddress);
                break;
            case R.id.btn_submit:
//                new BleUtil().connect(device,mBluetoothGattCallback);
                connect(rightAddress);
                break;
        }
    }

    BluetoothSocket mSocket;

    //先边右耳机 , 如失败则连接左耳机
    public void connect(String addr) {

//        showLoadingDialog();
        try {
            BluetoothDevice dev = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(addr);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD_MR1) {
                mSocket = dev.createInsecureRfcommSocketToServiceRecord(UUID.fromString(BleUUIDs.BT_SPP_UUID)); //加密传输，Android系统强制配对，弹窗显示配对码
            } else {
                mSocket = dev.createRfcommSocketToServiceRecord(UUID.fromString(BleUUIDs.BT_SPP_UUID)); //明文传输(不安全)，无需配对
            }
            // 开启子线程
            RxHelper.runInThread(this, new RxHelper.ISimperRxListener<Integer>() {
                @Override
                public Integer call() {

                    try {
                        mSocket.connect();
                        return 1;
                    } catch (IOException connectException) {
                        if (addr.equals(rightAddress)) {
                            connect(leftAddress);
                        } else {
                            try {
                                mSocket.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        return 0;
                    }
                }

                @Override
                public void onNext(Integer integer) {
                    dismissLoadingDialog();
                    if (integer == 1) {
                        showToast(R.string.conn_succ);
                    } else if (addr.equals(rightAddress)) {
                        showToast(R.string.conn_failed);
                    }
                }


                @Override
                public void onError(Throwable e) {
                    dismissLoadingDialog();
                    showToast(e.getMessage());
                }
            });

        } catch (Throwable e) {
            showToast(R.string.conn_error);
        }
    }

    public static void startBy(Context context, BluetoothDevice device, String leftAddress, String rightAddress, String advCount) {
        Intent intent = new Intent(context, DialogActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("BluetoothDevice", device);
        intent.putExtra("leftAddress", leftAddress);
        intent.putExtra("rightAddress", rightAddress);
        intent.putExtra("advCount", advCount);
        context.startActivity(intent);

    }


    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0, 0);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (animationDrawable != null)
            animationDrawable.stop();
    }
}
